#include "recvpacket.h"

RecvPacket::~RecvPacket()
{
    if(bodyObject != nullptr)delete bodyObject;
    if(ssoFrame != nullptr)delete ssoFrame;
    if(oicqResponse != nullptr)delete oicqResponse;
}

RecvPacket::RecvPacket(const QByteArray &data, const QByteArray &d2Key):DataReader(data)
{
    readInt(packSize).readInt(flag1).readByte(flag2).readByte(flag3);
    readBytes(uinString,LengthType::INT,-4);
    readAll(plainBody);
    if(flag2 == 2)TEA::setKey(QByteArray(16,0));
    else if(flag2 == 1)TEA::setKey(d2Key);
    else if(flag2 == 0){}//no encrypt
    else abort();
    if(flag2 != 0)plainBody = TEA::decrypt(plainBody);
    if(plainBody.size() == 0)abort();//decrypt error
    ssoFrame = new SsoFrame(plainBody);
    if(flag2 == 2)oicqResponse = new OicqResponse(ssoFrame->body);
    else {//0,1
        //call class to decode
    }

    //decode cmd (use QT reflection)
    int id = QMetaType::type(ssoFrame->commandName.replace('.','_'));
    if(id != 0){
        bodyObject = (CmdPacketRecv*)QMetaType::create(id);
        bodyObject->setData(flag2==2?oicqResponse->plainBody:ssoFrame->body).unpack();
        qDebug()<<"Parse Packet Success"<<ssoFrame->commandName<<"recvpacket.cpp";
    }else qDebug()<<"Unknown Packet"<<ssoFrame->commandName;
}
